package com.my.oschina.fragment;

import java.util.ArrayList;
import java.util.List;

import android.os.AsyncTask;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockListFragment;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.my.oschina.R;
import com.my.oschina.adapter.ListViewFriendAdapter;
import com.my.oschina.app.AppContext;
import com.my.oschina.app.AppException;
import com.my.oschina.bean.FriendList;
import com.my.oschina.bean.FriendList.Friend;

/**
 * 关注
 * 
 * @author XuShaoJie
 * @version 2013-06-28
 */
public class FollowFragment extends SherlockListFragment {

	private int mInstance = -1;

	private PullToRefreshListView mPullRefreshListView;
	private ListViewFriendAdapter mNewsAdapter;
	private View footerView;
	private List<Friend> lvNewsDataList = new ArrayList<Friend>();

	private AppContext appContext;// 全局Context

	public FollowFragment() {
		setRetainInstance(true);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		appContext = (AppContext) getSherlockActivity().getApplication();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (savedInstanceState != null) {
			mInstance = savedInstanceState.getInt("mInstance");
		}
		View view = inflater.inflate(R.layout.activity_ptr_list, container,
				false);
		mPullRefreshListView = (PullToRefreshListView) view
				.findViewById(R.id.pull_refresh_list);
		mPullRefreshListView.setMode(Mode.BOTH);
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		// 设置下拉列表事件监听器
		mPullRefreshListView
				.setOnRefreshListener(new OnRefreshListener<ListView>() {
					@Override
					public void onRefresh(
							PullToRefreshBase<ListView> refreshView) {
						// 下拉刷新触发，在这里开始刷新
						beginLoading(refreshView);
					}
				});

		// Add an end-of-list listener
		mPullRefreshListView
				.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
					@Override
					public void onLastItemVisible() {
						Toast.makeText(getSherlockActivity(), "End",
								Toast.LENGTH_SHORT).show();
					}
				});
		footerView = getSherlockActivity().getLayoutInflater().inflate(
				R.layout.listview_footer, null);
		mNewsAdapter = new ListViewFriendAdapter(getSherlockActivity(),
				lvNewsDataList, R.layout.friend_listitem);
		mPullRefreshListView.setAdapter(mNewsAdapter);

		// TODO
		// 第一次启动时候加载数据
		new GetFollowTask().execute();
	}

	/**
	 * 开始加载，并且显示加载中
	 * 
	 * @param refreshView
	 */
	private void beginLoading(PullToRefreshBase<ListView> refreshView) {
		String label = DateUtils.formatDateTime(appContext,
				System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
						| DateUtils.FORMAT_SHOW_DATE
						| DateUtils.FORMAT_ABBREV_ALL);
		// Update the LastUpdatedLabel
		refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

		// 加载数据异步处理任务
		new GetFollowTask().execute();
	}

	/**
	 * 加载数据AsyncTask
	 */
	private class GetFollowTask extends AsyncTask<String, Void, FriendList> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			getSherlockActivity().setSupportProgressBarIndeterminateVisibility(
					true);
		}

		@Override
		protected FriendList doInBackground(String... params) {
			try {
				return appContext.getFriendList(FriendList.TYPE_FOLLOWER, 0,
						true);
			} catch (AppException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(FriendList result) {
			super.onPostExecute(result);

			getSherlockActivity().setSupportProgressBarIndeterminateVisibility(
					false);
			// 如果是刷新的话，则先清除列表原先的数据
			lvNewsDataList.clear();
			lvNewsDataList.addAll(result.getFriendlist());
			mNewsAdapter.notifyDataSetChanged();
			// Call onRefreshComplete when the list has been refreshed.
			mPullRefreshListView.onRefreshComplete();

			if (result.getFriendlist().size() < 20) {
				mPullRefreshListView.setMode(Mode.PULL_FROM_START);
//				Toast.makeText(getSherlockActivity(), "Over",
//						Toast.LENGTH_SHORT).show();
				
			} else if (result.getFriendlist().size() == 20) {
				mPullRefreshListView.setMode(Mode.BOTH);
//				Toast.makeText(getSherlockActivity(), "More",
//						Toast.LENGTH_SHORT).show();
			}
		}
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt("mInstance", mInstance);
	}

}
